import { useState, useEffect, useContext } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { AuthContext } from '@/contexts/authContext';
import { useTheme } from '@/hooks/useTheme';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { aiService, ProductInfo, ConditionAssessment } from '@/lib/aiService';

// 商品详情接口
interface ProductDetail {
  id: string;
  title: string;
  price: number;
  originalPrice?: number;
  description: string;
  images: string[];
  category: string;
  location: string;
  postedAt: string;
  views: number;
  seller: {
    id: string;
    name: string;
    avatar?: string;
    rating: number;
    transactionCount: number;
  };
  tags: string[];
  condition: 'brand-new' | 'like-new' | 'good' | 'fair';
}

// 模拟商品数据
const mockProduct: ProductDetail = {
  id: '1',
  title: '九成新 MacBook Pro 2023',
  price: 8999,
  originalPrice: 11999,
  description: '2023年购买的MacBook Pro，配置为M3芯片，16GB内存，512GB固态硬盘。外观几乎全新，没有任何刮痕或损坏。电池健康度98%。包含原装充电器和包装盒。由于毕业换工作，所以出售。',
  images: [
    'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=laptop%20macbook%20pro%20new%20condition&sign=9aef334f65c07133b3bc1d6ad6a6a701',
    'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=laptop%20macbook%20pro%20keyboard%20closeup&sign=957f0e1ab06937ba7ff26e9fd2070f6a',
    'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=laptop%20macbook%20pro%20with%20charger&sign=8bebba0039252e23a86338b4a8db2d67'
  ],
  category: '电子产品',
  location: '主校区',
  postedAt: '2小时前',
  views: 156,
  seller: {
    id: 'seller1',
    name: '李明',
    avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=male%20college%20student%20avatar&sign=ce2e40061e9899bed92d3bab0ea79407',
    rating: 4.9,
    transactionCount: 128
  },
  tags: ['MacBook', '笔记本电脑', 'M3', '电子产品'],
  condition: 'like-new'
};

export default function ProductDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [product, setProduct] = useState<ProductDetail | null>(null);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [isAuthenticated] = useContext(AuthContext);
  const { theme } = useTheme();
  const [aiAssessment, setAiAssessment] = useState<ConditionAssessment | null>(null);

  // 获取商品详情
  useEffect(() => {
    // 模拟API请求
    setTimeout(() => {
      // 实际应用中应该根据id从API获取数据
      setProduct(mockProduct);
      
      // 获取商品后进行AI评估
      if (mockProduct) {
        assessProductCondition();
      }
    }, 500);
  }, [id]);

  // AI评估商品新旧程度
  const assessProductCondition = async () => {
    if (!product) return;
    
    try {
      const productInfo: ProductInfo = {
        title: product.title,
        description: product.description,
        category: product.category,
        images: product.images
      };
      
      const assessment = await aiService.assessProductCondition(productInfo);
      setAiAssessment(assessment);
    } catch (error) {
      console.error('AI评估失败:', error);
    }
  };

  // 加入购物车
  const handleAddToCart = () => {
    if (!isAuthenticated) {
      toast.warning('请先登录');
      navigate('/login');
      return;
    }
    
    // 模拟加入购物车
    toast.success('商品已加入购物车');
  };

  // 立即购买
  const handleBuyNow = () => {
    if (!isAuthenticated) {
      toast.warning('请先登录');
      navigate('/login');
      return;
    }
    
    // 模拟立即购买，直接跳转到订单确认页
    toast.success('即将跳转到订单确认页面');
    setTimeout(() => {
      navigate('/orders/new', { state: { productId: product?.id } });
    }, 1000);
  };

  // 联系卖家
  const handleContactSeller = () => {
    if (!isAuthenticated) {
      toast.warning('请先登录');
      navigate('/login');
      return;
    }
    
    // 模拟联系卖家
    toast.info('正在打开聊天窗口...');
  };

  // 条件状态文本映射
  const conditionText = {
    'brand-new': '全新',
    'like-new': '九成新',
    'good': '良好',
    'fair': '一般'
  };
  
  // 条件状态样式映射
  const conditionStyles = {
    'brand-new': 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300',
    'like-new': 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300',
    'good': 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300',
    'fair': 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300'
  };

  if (!product) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900")}>
      <div className="max-w-6xl mx-auto px-4 py-8">
        {/* 返回按钮 */}
        <button 
          onClick={() => navigate(-1)}
          className="mb-6 inline-flex items-center px-4 py-2 rounded-lg bg-white dark:bg-gray-800 shadow-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
        >
          <i className="fa-solid fa-arrow-left mr-2"></i>
          返回
        </button>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* 商品图片展示 */}
          <div className="space-y-4">
            <div className="rounded-2xl overflow-hidden bg-white dark:bg-gray-800 shadow-sm p-4">
              <img 
                src={product.images[currentImageIndex]} 
                alt={product.title}
                className="w-full h-80 object-cover rounded-xl"
              />
            </div>
            
            {/* 缩略图导航 */}
            <div className="flex gap-4 overflow-x-auto pb-2">
              {product.images.map((image, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentImageIndex(index)}
                  className={`flex-shrink-0 w-20 h-20 rounded-lg overflow-hidden border-2 ${
                    currentImageIndex === index 
                      ? 'border-indigo-500' 
                      : 'border-transparent hover:border-gray-300 dark:hover:border-gray-600'
                  }`}
                >
                  <img 
                    src={image} 
                    alt={`缩略图 ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                </button>
              ))}
            </div>
          </div>
          
          {/* 商品信息和操作 */}
          <div className="space-y-6">
            {/* 商品基本信息 */}
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
              <div className="flex items-center text-sm text-gray-500 dark:text-gray-400 mb-2">
                <span>{product.postedAt}</span>
                <span className="mx-2">·</span>
                <span>{product.views} 人浏览</span>
              </div>
              
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
                {product.title}
              </h1>
              
              <div className="mb-4">
                <div className="flex items-baseline">
                  <span className="text-3xl font-bold text-red-600 dark:text-red-400">¥{product.price}</span>
                  {product.originalPrice && (
                    <span className="ml-2 text-sm text-gray-500 dark:text-gray-400 line-through">
                      ¥{product.originalPrice}
                    </span>
                  )}
                </div>
                {product.originalPrice && (
                  <span className="text-xs text-red-600 dark:text-red-400">
                    已优惠 ¥{product.originalPrice - product.price}
                  </span>
                )}
              </div>
              
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">分类</span>
                  <span className="text-gray-900 dark:text-white">{product.category}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">新旧程度</span>
                  <span className="text-gray-900 dark:text-white">{conditionText[product.condition]}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">交易地点</span>
                  <span className="text-gray-900 dark:text-white">{product.location}</span>
                </div>
              </div>
              
              {/* AI评估结果 */}
              {aiAssessment && (
                <div className="mt-6 p-4 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800">
                  <h4 className="font-medium mb-2 text-indigo-800 dark:text-indigo-400 flex items-center">
                    <i className="fa-solid fa-robot mr-2"></i>
                    AI评估结果
                  </h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-700 dark:text-gray-300">预估新旧程度:</span>
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${conditionStyles[aiAssessment.condition]}`}>
                        {conditionText[aiAssessment.condition]}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-700 dark:text-gray-300">置信度:</span>
                      <span className="text-gray-900 dark:text-white">{aiAssessment.confidence}%</span>
                    </div>
                  </div>
                  <p className="mt-3 text-sm text-gray-700 dark:text-gray-300">
                    <span className="font-medium">评估理由:</span> {aiAssessment.reasoning}
                  </p>
                  {aiAssessment.suggestedPriceRange && (
                    <p className="mt-2 text-sm text-green-700 dark:text-green-400">
                      <span className="font-medium">建议价格范围:</span> {aiAssessment.suggestedPriceRange}
                    </p>
                  )}
                </div>
              )}
              
              {/* 标签 */}
              <div className="mt-4 flex flex-wrap gap-2">
                {product.tags.map((tag, index) => (
                  <span 
                    key={index} 
                    className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
            
            {/* 卖家信息 */}
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  {product.seller.avatar ? (
                    <img 
                      src={product.seller.avatar} 
                      alt={product.seller.name}
                      className="w-12 h-12 rounded-full object-cover mr-4"
                    />
                  ) : (
                    <div className="w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center mr-4">
                      <i className="fa-solid fa-user text-gray-400"></i>
                    </div>
                  )}
                  
                  <div>
                    <h3 className="font-medium text-gray-900 dark:text-white">{product.seller.name}</h3>
                    <div className="flex items-center mt-1">
                      <div className="flex items-center text-yellow-500 mr-2">
                        {Array(5).fill(0).map((_, i) => (
                          <i 
                            key={i} 
                            className={`fa-solid ${i < Math.floor(product.seller.rating) ? 'fa-star' : 'fa-star-half-stroke'}`}
                            style={{ fontSize: '12px' }}
                          ></i>
                        ))}
                      </div>
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        {product.seller.rating} ({product.seller.transactionCount} 笔交易)
                      </span>
                    </div>
                  </div>
                </div>
                
                <button
                  onClick={handleContactSeller}
                  className="px-4 py-2 bg-indigo-100 dark:bg-indigo-900 text-indigo-600 dark:text-indigo-400 rounded-lg hover:bg-indigo-200 dark:hover:bg-indigo-800 text-sm font-medium"
                >
                  <i className="fa-solid fa-comment mr-1"></i>
                  联系卖家
                </button>
              </div>
            </div>
            
            {/* 操作按钮 */}
            <div className="flex gap-4">
              <button
                onClick={handleAddToCart}
                className="flex-1 py-3 px-6 bg-indigo-600 dark:bg-indigo-500 text-white rounded-lg hover:bg-indigo-700 dark:hover:bg-indigo-600 text-sm font-medium flex items-center justify-center"
              >
                <i className="fa-solid fa-cart-shopping mr-2"></i>
                加入购物车
              </button>
              
              <button
                onClick={handleBuyNow}
                className="flex-1 py-3 px-6 bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 text-sm font-medium flex items-center justify-center"
              >
                <i className="fa-solid fa-bolt mr-2"></i>
                立即购买
              </button>
            </div>
          </div>
        </div>
        
        {/* 商品描述 */}
        <div className="mt-8 bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">商品详情</h2>
          
          <div className="prose dark:prose-invert max-w-none">
            <p className="text-gray-700 dark:text-gray-300 whitespace-pre-line">
              {product.description}
            </p>
            
            {/* 额外信息 */}
            <div className="mt-6 border-t border-gray-200 dark:border-gray-700 pt-6">
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-3">基本信息</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex">
                  <span className="text-gray-600 dark:text-gray-400 w-24">商品编号:</span>
                  <span className="text-gray-900 dark:text-white">{product.id}</span>
                </div>
                <div className="flex">
                  <span className="text-gray-600 dark:text-gray-400 w-24">发布时间:</span>
                  <span className="text-gray-900 dark:text-white">{product.postedAt}</span>
                </div>
                <div className="flex">
                  <span className="text-gray-600 dark:text-gray-400 w-24">浏览次数:</span>
                  <span className="text-gray-900 dark:text-white">{product.views}</span>
                </div>
                <div className="flex">
                  <span className="text-gray-600 dark:text-gray-400 w-24">交易方式:</span>
                  <span className="text-gray-900 dark:text-white">当面交易或邮寄</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* 推荐商品 */}
        <div className="mt-8">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">猜你喜欢</h2>
          
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {[1, 2, 3, 4].map((item) => (
              <div 
                key={item} 
                className="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden cursor-pointer hover:shadow-md transition-all"
              >
                <div className="h-40 overflow-hidden">
                  <img 
                    src={`https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=secondhand%20laptop%20computer%20${item}`} 
                    alt={`推荐商品 ${item}`}
                    className="w-full h-full object-cover"
                  />
                </div>
                <div className="p-3">
                  <h3 className="font-medium text-gray-900 dark:text-white text-sm line-clamp-1">
                    二手笔记本电脑 {item}
                  </h3>
                  <div className="flex items-center justify-between mt-2">
                    <span className="text-sm font-bold text-indigo-600 dark:text-indigo-400">
                      ¥{5000 + item * 1000}
                    </span>
                    <span className="text-xs text-gray-500 dark:text-gray-400">
                      {item}天前
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}